package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.thread.UserThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component   //HandlerInterceptor
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取令牌
        String authorization = request.getHeader("authorization");
        //判断令牌是否为空
        if (StringUtils.isEmpty(authorization)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("用户未登录");
        }
        //验证令牌
        Claims claims = tokenService.parseToken(authorization);
        if (claims == null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("用户未登录");
        }
        Long userId = MapUtil.get(claims, "userId", Long.class);
        log.info("小程序用户id:{}", userId);
        UserThreadLocal.set(userId);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
        UserThreadLocal.remove();
    }
}
